package com.example.findtherinbow.utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

public class GsonUtil {

    private Gson gson;
    private static GsonUtil instance;

    private GsonUtil() {
        gson = new Gson();
    }

    public static synchronized GsonUtil getInstance() {
        if (instance == null) {
            instance = new GsonUtil();
        }
        return instance;
    }

    // 将对象转换为JSON字符串
    public String toJson(Object object) {
        return gson.toJson(object);
    }

    // 将JSON字符串转换为对象
    public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException {
        return gson.fromJson(json, classOfT);
    }

    // 将JSON字符串转换为List对象
    public <T> List<T> jsonToList(String json, Class<T> classOfT) throws JsonSyntaxException {
        Type listType = TypeToken.getParameterized(List.class, classOfT).getType();
        return gson.fromJson(json, listType);
    }
}

